<?php

namespace app\admin\controller\kuyou;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;
/**
 * 生产计划
 *
 * @icon fa fa-circle-o
 */
class Plan extends Backend
{

    /**
     * Procedure模型对象
     * @var \app\admin\model\kuyou\Plan
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\kuyou\Plan;
        $setData = (new Goods())->getSetData();
        $this->assign('set', $setData['setList']);
        $this->assignconfig('set',$setData['setList']);
        $this->assign('nowmenu', $setData['nowmenu']);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index($ids = null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $list_k=>$list_v){
                $list[$list_k]['workshop_id'] = Db::name('kuyou_workshop')->where(['id'=>$list_v['workshop_id']])->column('name');

                $goods_list = Db::name('kuyou_plan_info')->where(['plan_id'=>$list_v['id']])->field('goods_name,number')->select();
                $str = '';
                foreach ($goods_list as $goods_list_k=>$goods_list_v){
                    $str .= $goods_list_v['goods_name'].'*'.$goods_list_v['number'].' ';
                }
                $list[$list_k]['goods_info'] = $str;
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig('ids',$ids);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $examine= Db::name('kuyou_sets')->where(['name'=>'examine'])->value('is_checked');
                foreach ($params['goods_code'] as $k=>$v){
                    if(!empty($v)) {//有产品编号
                        $status = true;
                    }
                }
                if(!isset($status)){
                    $this->error(__('Please fill in the detailed data'));
                }
                $number = 0;$all_money = 0;$data=[];
                foreach ($params['goods_code'] as $k=>$v){
                    if(!empty($v)){//有产品编号
                        $number += (float)$params['number'][$k];
                        $all_money += (float)$params['all_money'][$k];
                        $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v])->field('id,goods_code,goods_name')->find();
                        $data[] = [
                            'goods_id'      =>  $goods['id'],
                            'goods_code'    =>  $goods['goods_code'],
                            'goods_name'    =>  $goods['goods_name'],
                            'unit_id'       =>  (float)$params['goods_unit'][$k],
                            'purchase'      =>  (float)$params['unit_price'][$k],
                            'number'        =>  (float)$params['number'][$k],
                            'money'         =>  (float)$params['all_money'][$k],
                            'default_unit'  =>  (float)$params['default_unit'][$k],
                            'basic_nmber'   =>  (float)$params['basic_nmber'][$k],
                            'createtime'    => time(),
                            'updatetime'    => time(),
                        ];
                    }
                }
                if(empty($data)){
                    $this->error(__('Please fill in the detailed data'));
                }else{
                    $admin = Session::get('admin');
                    $row = [
                        'purchase_code' =>  $params['purchase_code'],
                        'purchase_time' =>  strtotime($params['purchase_time']),
                        'delivery_time' =>  strtotime($params['delivery_time']),
                        'workshop_id'   =>  $params['workshop_id'],
                        'remark'        =>  $params['remark'],
                        'preparation_id'=>$admin['id'],
                        'operation_id'  =>$admin['id'],
                        'createtime'    => time(),
                        'updatetime'    => time(),
                    ];
                    if($this->model->where(['purchase_code'=>trim($params['purchase_code'])])->find()){
                        $this->error(__('The document number is already occupied'));
                    }
                }

                $result = false;
                Db::startTrans();
                try {
                    if(!empty($row)){
                        $result = $this->model->insertGetId($row);
                    }

                    foreach ($data as $data_k=>$data_v){
                        $data[$data_k]['plan_id'] = $result;
                    }
                    Db::name('kuyou_plan_info')->insertAll($data);
                    $count = Db::name('kuyou_plan_info')->where(['plan_id'=>$result])->field('sum(number) as number,sum(money) as money')->select();
                    if(isset($count[0]['number'])){
                        $this->model->where(['id'=>$result])->update(['number'=>$count[0]['number'],'all_money'=>$count[0]['money']]);
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if($examine!=1){
                        try {
                            $exa = $this->examine($result,1);
                        } catch (Exception $e) {
                        }
                        if(!isset($exa) || $exa['status']!=1){
                            $exa = $this->examine($result,1);
                            try {
                                $this->del($result);
                            } catch (Exception $e) {
                            }
                            $this->error($exa['msg']);
                        }
                    }
                    $this->success(__('Added successfully'));
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $code = (new Goods())->getCodes('',31);
        $this->view->assign("code", $code);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $examine= Db::name('kuyou_sets')->where(['name'=>'examine'])->value('is_checked');
                foreach ($params['goods_code'] as $k=>$v){
                    if(!empty($v)) {//有产品编号
                        $status = true;
                    }
                }
                if(!isset($status)){
                    $this->error(__('Please fill in the detailed data'));
                }
                $number = 0;$all_money = 0;$data=[];
                foreach ($params['goods_code'] as $k=>$v){
                    if(!empty($v)){//有产品编号
                        $number += (float)$params['number'][$k];
                        $all_money += (float)$params['all_money'][$k];
                        $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v])->field('id,goods_code,goods_name')->find();
                        $data[] = [
                            'goods_id'      =>  $goods['id'],
                            'goods_code'    =>  $goods['goods_code'],
                            'goods_name'    =>  $goods['goods_name'],
                            'unit_id'       =>  (float)$params['goods_unit'][$k],
                            'purchase'      =>  (float)$params['unit_price'][$k],
                            'number'        =>  (float)$params['number'][$k],
                            'money'         =>  (float)$params['all_money'][$k],
                            'default_unit'  =>  (float)$params['default_unit'][$k],
                            'basic_nmber'   =>  (float)$params['basic_nmber'][$k],
                            'createtime'    => time(),
                            'updatetime'    => time(),
                        ];
                    }
                }
                if(empty($data)){
                    $this->error(__('Please fill in the detailed data'));
                }else{
                    $admin = Session::get('admin');
                    $rowdata = [
                        'purchase_code' =>  $params['purchase_code'],
                        'purchase_time' =>  strtotime($params['purchase_time']),
                        'delivery_time' =>  strtotime($params['delivery_time']),
                        'workshop_id'   =>  $params['workshop_id'],
                        'remark'        =>  $params['remark'],
                        'operation_id'  =>$admin['id'],
                        'updatetime'    => time(),
                    ];
                    if($this->model->where(['purchase_code'=>trim($params['purchase_code']),'id'=>['<>',$ids]])->find()){
                        $this->error(__('The document number is already occupied'));
                    }
                }

                $result = false;
                Db::startTrans();
                try {
                    if($examine!=1 && $row['examine_status']==1){
                        $this->examine($ids,2);
                    }

                    if(!empty($rowdata)){
                        $result = $this->model->where(['id'=>$row['id']])->update($rowdata);
                    }

                    foreach ($data as $data_k=>$data_v){
                        $data[$data_k]['plan_id'] = $row['id'];
                    }
                    Db::name('kuyou_plan_info')->where(['plan_id'=>$row['id']])->delete();
                    Db::name('kuyou_plan_info')->insertAll($data);
                    $count = Db::name('kuyou_plan_info')->where(['plan_id'=>$row['id']])->field('sum(number) as number,sum(money) as money')->select();
                    if(isset($count[0]['number'])){
                        Db::name('kuyou_plan')->where(['id'=>$row['id']])->update(['number'=>$count[0]['number'],'all_money'=>$count[0]['money']]);
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if($examine!=1){
                        try {
                            $exa = $this->examine($ids,1);
                        } catch (Exception $e) {
                        }
                        if(!isset($exa) || $exa['status']!=1){
                            $this->error(__('No rows were inserted'));
                        }
                    }
                    $this->success(__('Edited successfully'));
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $purchase_info = Db::name('kuyou_plan_info')->where(['plan_id'=>$row['id']])->select();
        foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
            $purchase_info[$purchase_info_k]['unit'] = json_decode((new GoodsPurchase())->getUnit($purchase_info_v['goods_code']),true);
        }
        $this->view->assign("purchase_info", $purchase_info);

        $this->view->assign("row", $row);

        //审核禁止输入
        $examine_set= Db::name('kuyou_sets')->where(['name'=>'examine'])->value('is_checked');
        if($examine_set==1 && $row['examine_status']==1){
            $this->assign('exclass','hiddens');
        }
        $this->assignconfig("examine_status", $row['examine_status']);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $examine= Db::name('kuyou_sets')->where(['name'=>'examine'])->value('is_checked');
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {

                    if($v['examine_status']==1 && $examine==1){
                        exception(__('Cannot delete audited data'));return;
                    }elseif ($v['examine_status']==1 && $examine!=1){
                        try {
                            $this->examine($v['id'],2);
                        } catch (Exception $e) {
                        }
                    }

                    $count += $v->delete();
                    Db::name('kuyou_plan_info')->where(['plan_id'=>$v['id']])->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    //审核/反审核
    public function examine($ids = null,$examine=1){
        $examine_set= Db::name('kuyou_sets')->where(['name'=>'examine'])->value('is_checked');
        if(empty($ids)){
            if($examine_set!=1){
                return ['status'=>0,'msg'=>__('System error')];
            }
            $this->error(__('Please select the data to be operated on'));
        }
        $admin = Session::get('admin');
        if($examine==1){
            $list = $this->model->where(['id'=>['in',$ids],'examine_status'=>'0'])->select();
            Db::startTrans();
            try {
                $result = $this->model->where(['id'=>['in',$ids],'examine_status'=>'0'])
                    ->update(['examine_status'=>1,'examine_id'=>$admin['id'],'examine_time'=>time(),'operation_id'=>$admin['id']]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if(isset($result) && $result !== false){
                if($examine_set!=1){
                    return ['status'=>1,'msg'=>__('Operation successful')];
                }
                $this->success(sizeof($list).__('The data review was successful'));
            }else{
                if($examine_set!=1){
                    return ['status'=>0,'msg'=>__('operation failed')];
                }
                $this->error(__('Audit failed'));
            }
        }else{
            $list = $this->model->where(['id'=>['in',$ids],'examine_status'=>'1'])->select();
            if(empty($list)){
                if($examine_set!=1){
                    return ['status'=>0,'msg'=>__('operation failed')];
                }
                $this->error(__('Please select the data that needs to be de audited'));
            }
            foreach ($list as $list_k=>$list_v){
                $order = Db::name('kuyou_production')->where(['plan_code'=>$list_v['purchase_code']])->column('id');
                if(!empty($order)){
                    if($examine_set!=1){
                        return ['status'=>0,'msg'=>__('Cannot manipulate data of generated production orders')];
                    }
                    $this->error(__('Cannot reverse audit data of generated production orders'));
                }
                $order = Db::name('kuyou_outsourcing')->where(['plan_code'=>$list_v['purchase_code']])->column('id');
                if(!empty($order)){
                    if($examine_set!=1){
                        return ['status'=>0,'msg'=>__('Cannot manipulate data of generated outsourcing orders')];
                    }
                    $this->error(__('Cannot reverse audit data of generated outsourcing orders'));
                }
            }
            $admin = Session::get('admin');
            Db::startTrans();
            try {
                $result = $this->model->where(['id'=>['in',$ids],'examine_status'=>'1'])
                    ->update(['examine_status'=>'0','examine_id'=>0,'examine_time'=>'','operation_id'=>$admin['id']]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if(isset($result) && $result !== false){
                if($examine_set!=1){
                    return ['status'=>1,'msg'=>__('Operation successful')];
                }
                $this->success(sizeof($list).__('The data has been successfully de audited'));
            }else{
                if($examine_set!=1){
                    return ['status'=>0,'msg'=>__('operation failed')];
                }
                $this->error(__('Anti audit failed'));
            }
        }
    }

    public function choseplan(){
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $data = input();
            if(isset($data['purchase_code'])){
                $detail = Db::name('kuyou_plan')->where(['purchase_code'=>$data['purchase_code']])->find();
                if($detail){
                    $info = Db::name('kuyou_plan_info')->where(['plan_id'=>$detail['id']])->select();
                    foreach ($info as $info_k=>$info_v){
                        $info[$info_k]['unit'] = Db::name('kuyou_unit')->where(['id'=>$info_v['unit_id']])->find();
                    }
                }else{
                    $info = [];
                }
                $result = array("total" => sizeof($info), "rows" => $info);
                return json($result);
            }else{
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
                $list = $this->model
                    ->where($where)
                    ->where(['examine_status'=>'1'])
                    ->order($sort, $order)
                    ->paginate($limit);
                foreach ($list as $list_k=>$list_v){
                    $list[$list_k]['workshop_id'] = Db::name('kuyou_workshop')->where(['id'=>$list_v['workshop_id']])->column('name');
                }
                $result = array("total" => $list->total(), "rows" => $list->items());
                return json($result);
            }
        }
        return $this->view->fetch();
    }
}
